package com.net.xpay.backend.scheduler;


import com.net.xpay.common.domain.notify.FlexibleStaffAuthenticationNotifyRecord;
import com.net.xpay.common.manager.FlexibleStaffAuthenticationManager;
import com.net.xpay.common.manager.notify.FlexibleStaffAuthenticationNotifyRecordManager;
import com.net.xpay.common.service.FlexibleStaffAuthenticationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 2019/7/15 16:28

 * 零工视频核验
 */
@Slf4j
@Component
public class FlexibleStaffAuthenticationScheduler {

    @Autowired
    private FlexibleStaffAuthenticationManager flexibleStaffAuthenticationManager;

    @Autowired
    private FlexibleStaffAuthenticationNotifyRecordManager flexibleStaffAuthenticationNotifyRecordManager;

    @Autowired
    private FlexibleStaffAuthenticationService flexibleStaffAuthenticationService;

    /**
     * 跟新核身结果
     */
    @Scheduled(cron = "*/1 * * * * *")
    public void updateFlexibleStaffAuthentication() {
        List<Long> ids = flexibleStaffAuthenticationManager.listInitIds();
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        for (Long id : ids) {
            try {
                flexibleStaffAuthenticationService.updateFlexibleStaffAuthentication(id);
            } catch (Exception e) {
                log.error("updateFlexibleStaffAuthentication id={}", id, e);
            }
        }

    }


    /**
     * 清理过期的数据
     */
    @Scheduled(cron = "0 0 2 * * *")
    public void cleanFlexibleStaffAuthenticationNotifyRecord() {
        log.info("cleanFlexibleStaffAuthenticationNotifyRecord start");

        //只保留一个月
        LocalDateTime deadline = LocalDateTime.now().minusMonths(1L);
        flexibleStaffAuthenticationNotifyRecordManager.deleteFinishedRecord(deadline);

        log.info("cleanFlexibleStaffAuthenticationNotifyRecord end");
    }

    /**
     * 回调通知
     */
    @Scheduled(cron = "*/2 * * * * *")
    public void notifyFlexibleStaffAuthenticationNotifyRecord() {
        List<Long> ids = flexibleStaffAuthenticationNotifyRecordManager.listWaitNotifyRecordIds(20);

        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        for (Long id : ids) {
            try {
                FlexibleStaffAuthenticationNotifyRecord record = flexibleStaffAuthenticationNotifyRecordManager.getById(id);
                flexibleStaffAuthenticationService.notifyRecord(record);
            } catch (Exception e) {
                log.info("notifyFlexibleStaffAuthenticationNotifyRecord failed|id={}", id, e);
            }
        }
    }


}
